<?php

namespace iBrand\Shop\Backend\Http\Controllers;


use iBrand\Component\Goods\Models\Goods;
use iBrand\Component\Goods\Models\Season;
use iBrand\Store\Backend\Model\Models;
use iBrand\Store\Backend\Model\Spec;
use Illuminate\Http\Request;
use iBrand\Shop\Core\Models\O2oGoods;
use iBrand\Shop\Core\Models\O2oGoodsProducts;
use iBrand\Shop\Backend\Repository\O2oGoodsRepository;
use iBrand\Shop\Backend\Repository\O2oGoodsProductsRepository;
use iBrand\Store\Backend\Repositories\ProductRepository;
use iBrand\Store\Backend\Service\GoodsService;
use Validator;
use DB;
use Excel;
use Encore\Admin\Facades\Admin as LaravelAdmin;
use Encore\Admin\Layout\Content;

class GoodsController extends Controller
{
    protected $goodsRepository;
    protected $productRepository;
    protected $product;
    protected $goodsService;

    protected static $errorSku;
    protected static $successSkuNum;
    protected static $goodsID;

    public function __construct(O2oGoodsRepository $goodsRepository,
                                O2oGoodsProductsRepository $productRepository,
                                GoodsService $goodsService,
                                ProductRepository $repository)
    {
        $this->goodsRepository = $goodsRepository;
        $this->productRepository = $productRepository;
        $this->goodsService = $goodsService;
        $this->product = $repository;
    }

    public function index()
    {
        $sold_out = request('sold_out');
        $criteria['status'] = $sold_out == 'ACTIVITY' ? 1 : 0;
        $criteria['shop_id'] = session('shop_id');

        $seasons = Season::all();
        $years = $this->getYearList();

        $where = [];
        if ($value = request('value')) {
            $where['goods_no'] = ['like', '%' . $value . '%'];
        }

        if ($year = request('year')) {
            $where['year'] = $year;
        }
        if ($searon = request('season_id')) {
            $where['season_id'] = $searon;
        }

        $ids = $this->goodsRepository->getGoodsIdsByCriteria($where);


        $goods = $this->goodsRepository->getGoodsPaginate($criteria, $ids);


        return LaravelAdmin::content(function (Content $content) use ($goods, $seasons, $years) {

            $content->header('商品列表');

            if (session()->has('shop_name')) {

                $content->description(session('shop_name'));
            }

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '商品列表', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '商品列表']
            );

            $content->body(view("shop-backend::goods.index", compact('goods', 'seasons', 'years')));
        });
    }


    public function editGoods()
    {
        $goods = O2oGoods::find(request('id'));
        $goods_info = Goods::find($goods->goods_id);

        //获取所选模型下规格数据
        $model = Models::find($goods_info->model_id);
        $spec = Spec::whereIn('id', $model->spec_ids)->get();

        $specData = $this->goodsService->handleInitSpecData($spec, $goods->goods_id, $goods->shop_id);

        return LaravelAdmin::content(function (Content $content) use ($goods, $goods_info, $specData) {

            $content->header('编辑商品');

            if (session()->has('shop_name')) {

                $content->description(session('shop_name'));
            }

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '编辑商品', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '商品列表']
            );

            $content->body(view("shop-backend::goods.includes.edit_goods", compact('goods', 'goods_info', 'specData')));
        });

    }

    public function saveGoods(Request $request)
    {
        $id = $request->input('id');
        $can_get_point = $request->input('can_get_point');
        $point_deduction = $request->input('point_deduction');
        $is_discount = $request->input('is_discount');

        $o2oGoods = O2oGoods::find($id);
        //  $price = $o2oGoods->goods->market_price;
        $price = 0;
        if ($is_discount) {
            $point_deduction = 0;
            $can_get_point = 0;
            $price = $request->input('discount_price');
        }

        $o2oGoods->point_deduction = $point_deduction;
        $o2oGoods->can_get_point = $can_get_point;
        $o2oGoods->is_discount = $is_discount;
        $o2oGoods->discount_price = $price;
        $o2oGoods->save();

        return $this->ajaxJson();
    }


    public function editBatchGoods()
    {
        if (request('ids') == 'all') {
            $ids = request('ids');
        } else {
            $ids = implode(',', request('ids'));
        }

        $value = request('value');
        $sold_out = request('sold_out');
        $shop_id = session('shop_id');

        return view("shop-backend::goods.includes.edit_batch_goods", compact('ids', 'value', 'sold_out', 'shop_id'));


    }

    public function saveBatchGoods(Request $request)
    {
        $input = $request->except('_token', 'file');

        $data['point_deduction'] = $input['point_deduction'];
        $data['can_get_point'] = $input['can_get_point'];
        $data['is_discount'] = $input['is_discount'];
        $ids = explode(',', $input['ids']);
        O2oGoods::whereIn('id', $ids)->update($data);

        return $this->ajaxJson();
    }

    /**
     * 是否可使用积分抵扣
     */
    public function pointDeductionSetting()
    {
        $shop_id = session('shop_id');
        $pointSettings = settings($shop_id . '_shop_point_disable');

        return LaravelAdmin::content(function (Content $content) use ($pointSettings, $shop_id) {

            $content->header('全店积分抵扣设置');

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '全店积分抵扣设置', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '积分抵扣设置']
            );

            $content->body(view("shop-backend::goods.includes.setting", compact('pointSettings', 'shop_id')));
        });
    }

    public function savePointDeductionSetting(Request $request)
    {
        $shop_id = session('shop_id');
        $setting_name = $shop_id . '_shop_point_disable';

        $value = $request->input('shop_point_disable');

        $data[$setting_name] = $value;
        $data['shop_get_point'] = $request->input('shop_get_point');
        $data['shop_point_order_limit'] = $request->input('shop_point_order_limit');
        $data['shop_point_proportion'] = $request->input('shop_point_proportion');
        $data['shop_new_user_reduce_'.$shop_id] = $request->input('shop_new_user_reduce');
        \Log::info($data);
        settings()->setSetting($data);

        return $this->ajaxJson(true, [], 200, '保存成功');
    }

    private function getYearList()
    {
        $year = date('Y', time());
        $before = $year - env('goods_year_before', 3);
        $result = [];
        for ($i = $before; $i <= $year; $i++) {
            $result[] = ['name' => $i . '上', 'id' => $i];
            $result[] = ['name' => $i . '下', 'id' => $i . '.5'];
        };

        return $result;
    }

}